<?php
class Image {
    /* 图片保存的路径 */
    private $root_path = '';
    private $save_path = '';
    private $save_name = '';
    private $name = '';
    private $image = '';
    private $new_image = null;
    public function __construct($file){
        $config_default = Yaf_Registry::get('config');
        $this->root_path = $config_default->file->root_path;
        $this->file = $file;
    }
    public function __get($name) {
        return $this->$name;
    }
    
    public function __set($name,$value){
        $this->$name = $value;
    }

    public function __isset($name){
        return isset($this->$name);
    }

    public function thumb($name,$width, $height){
        $image_info = getimagesize($name);
        $source = $this->createfromimage($name,$image_info);
        $size = $this->getNewSize($width, $height,$image_info);
        $im = $this->kidOfImage($source, $size,$image_info);            
        return $this->createNewImage($im,$image_info);
    }

    public function make($file){
        $model = new ConfigModel;
        $basic = $model->getBasic();
        $is_water_mark = $basic['watermark_dimension'];
        $show = $model->getShow();
        $temp = $file;
        $thumb = [
            $show['thumb_width'],
            $show['thumb_height']
        ];
        $default = [
            $show['image_width'],
            $show['image_height']
        ];

        $image = $file['src'];
        $water_image = $basic['watermark'];
        // if(!empty(thumb)){
        //     $thumb_image = $this->thumb($file['src'],$show['thumb_width'], $show['image_height']);
        //     $this->waterMark($thumb);
        // }else{
        //     $this->waterMark($thumb);
        // }
        $file = [
            'goods_picture'=>'',
            'goods_picture_proto'=>'',
            'goods_picture_thumb' => '',
        ];
        $file['goods_picture'] = $image;
        if(empty($default)){
            $file['goods_picture_proto'] = $temp['src'];

        }else{
            $new_image = $this->thumb($temp['src'],$default[0], $default[1]);
            $file['goods_picture_proto'] = $new_image;
            
        }
        if($is_water_mark == 1){
            // $file['goods_picture_proto'] = $this->waterMark($file['goods_picture_proto'],$basic['watermark'],$basic['watermake_optic']);
            $file['goods_picture_proto'] = $this->waterMark($file['goods_picture_proto'],$water_image,$basic['watermark_dimension']);
        }
        if(empty($thumb)){
            $file['goods_picture_thumb'] = $file['goods_picture_proto'];
        }else{
            $thumb_image = $this->thumb($file['goods_picture_proto'],$thumb[0],$thumb[1]);
            $file['goods_picture_thumb'] = $thumb_image;
        }
        $temp = array_merge($temp,$file);
        return $temp;
        // var_dump($temp);
    }

    /**
     * 为图片添加水印
     * @param  string $groundName 背景图片，即需要加水印的图片，暂只支持GIF,JPG,PNG格式
     * @param  string $waterName 图片水印，即作为水印的图片，暂只支持GIF,JPG,PNG格式
     * @param  int $waterPos    水印位置，有10种状态，0为随机位置；
     *                1为顶端居左，2为顶端居中，3为顶端居右；
     *                4为中部居左，5为中部居中，6为中部居右；
     *                7为底端居左，8为底端居中，9为底端居右；
     * @param  string $qz     加水印后的图片的文件名在原文件名前面加上这个前缀
     * @return  mixed        是生成水印后的图片名称,失败返回false
     */
    public function waterMark($groundName, $waterName, $waterPos=0){
        /*水印图片和背景图片必须都要存在*/
        if(file_exists($waterName)){
            $src_info = getimagesize($groundName);
            
            $waterInfo = getimagesize($waterName);
            /*如果背景比水印图片还小，就会被水印全部盖住*/
            if(!$pos = $this->position($src_info, $waterInfo, $waterPos)){
                echo '水印不应该比背景图片小！';
                return false;
            }
            $src_source = $this->createfromimage($groundName,$src_info);
            $waterImg = $this->createfromimage($waterName, $waterInfo); //获取水印图片资源
            
            /* 调用私有方法将水印图像按指定位置复制到背景图片中 */
            $groundImg = $this->copyImage($src_source, $waterImg, $pos, $waterInfo);
            /* 通过本类的私有方法，保存加水图片并返回新图片的名称，默认以"wa_"为前缀 */
            return $this->createNewImage($groundImg, $src_info);
 
        }else{
            echo '图片或水印图片不存在！';
            return false;
        }
    }
 
    /**
     * 在一个大的背景图片中剪裁出指定区域的图片
     * @param  string $name  需要剪切的背景图片
     * @param  int $x     剪切图片左边开始的位置
     * @param  int $y     剪切图片顶部开始的位置
     * @param  int $width   图片剪裁的宽度
     * @param  int $height   图片剪裁的高度
     * @param  string $qz   新图片的名称前缀
     * @return  mixed      裁剪后的图片名称,失败返回false;
     */
    public function cut($x, $y, $width, $height){
        $imgInfo=$this->getInfo();         //获取图片信息
        /* 裁剪的位置不能超出背景图片范围 */
        if( (($x+$width) > $imgInfo[0]) || (($y+$height) > $imgInfo[1])){
            echo "裁剪的位置超出了背景图片范围!";
            return false;
        }
 
        $back = $this->getImg($imgInfo);     //获取图片资源
        /* 创建一个可以保存裁剪后图片的资源 */
        $cutimg = imagecreatetruecolor($width, $height);
        /* 使用imagecopyresampled()函数对图片进行裁剪 */
        imagecopyresampled($cutimg, $back, 0, 0, $x, $y, $width, $height, $width, $height);
        imagedestroy($back);
        /* 通过本类的私有方法，保存剪切图并返回新图片的名称，默认以"cu_"为前缀 */
        return $this->createNewImage($cutimg,$imgInfo);
    }
 
    /* 内部使用的私有方法，用来确定水印图片的位置 */
    private function position($groundInfo, $waterInfo, $waterPos){
        /* 需要加水印的图片的长度或宽度比水印还小，无法生成水印 */
        if( ($groundInfo[0]<$waterInfo[0]) || ($groundInfo[1]<$waterInfo[1]) ) {
            return false;
        }
        switch($waterPos) {
        case 1:     //1为顶端居左
            $posX = 0;
            $posY = 0;
            break;
        case 2:     //2为顶端居中
            $posX = ($groundInfo[0] - $waterInfo[0]) / 2;
            $posY = 0;
            break;
        case 3:     //3为顶端居右
            $posX = $groundInfo[0] - $waterInfo[0];
            $posY = 0;
            break;
        case 4:     //4为中部居左
            $posX = 0;
            $posY = ($groundInfo[1] - $waterInfo[1]) / 2;
            break;
        case 5:     //5为中部居中
            $posX = ($groundInfo[0] - $waterInfo[0]) / 2;
            $posY = ($groundInfo[1] - $waterInfo[1]) / 2;
            break;
        case 6:     //6为中部居右
            $posX = $groundInfo[0] - $waterInfo[0];
            $posY = ($groundInfo[1] - $waterInfo[1]) / 2;
            break;
        case 7:     //7为底端居左
            $posX = 0;
            $posY = $groundInfo[1] - $waterInfo[1];
            break;
        case 8:     //8为底端居中
            $posX = ($groundInfo[0] - $waterInfo[0]) / 2;
            $posY = $groundInfo[1] - $waterInfo[1];
            break;
        case 9:     //9为底端居右
            $posX = $groundInfo[0] - $waterInfo[0];
            $posY = $groundInfo[1] - $waterInfo[1];
            break;
        case 0:
        default:    //随机
            $posX = rand(0,($groundInfo[0] - $waterInfo[0]));
            $posY = rand(0,($groundInfo[1] - $waterInfo[1]));
            break;
        }
        return array("posX"=>$posX, "posY"=>$posY);
    }
 
    /* 内部使用的私有方法，用于获取图片的属性信息（宽度、高度和类型） */
    public function getInfo($name) {
        $data = getimagesize($this->image);
         return $data;
    }
 
    public function createfromimage($name,$image_info){
         switch ($image_info[2]) {
        case 1:         //gif
            $img = imagecreatefromgif($name);  
          break;
        case 2:         //jpg
            $img = imagecreatefromjpeg($name);
            break;
        case 3:         //png
            $img = imagecreatefrompng($name);
            break;
        default:
            return false;
            break;
        }
        return $img;
    }
 
    public function getNewSize($width, $height, $imgInfo){
        $size["width"] = $imgInfo[0];     //原图片的宽度
        $size["height"] = $imgInfo[1];    //原图片的高度
 
        if($width < $imgInfo[0]){
            $size["width"]=$width;          //缩放的宽度如果比原图小才重新设置宽度
        }
 
        if($height < $imgInfo[1]){
            $size["height"] = $height;        //缩放的高度如果比原图小才重新设置高度
        }
        /* 等比例缩放的算法 */
        if($imgInfo[0]*$size["width"] > $imgInfo[1] * $size["height"]){
            $size["height"] = round($imgInfo[1]*$size["width"]/$imgInfo[0]);
        }else{
            $size["width"] = round($imgInfo[1]*$size["height"]/$imgInfo[1]);
        }
 
        return $size;
    }
 
    public function createNewImage($newImg, $image_info){
        $width = imagesx($newImg);
        $height = imagesy($newImg);
        // var_dump($this->file);
        $path = $this->file['root_path'].$this->file['save_path'].$this->file['name'].'.'.$width.'x'.$height;
        $name = '';
        switch ($image_info[2]) {
        case 1:       //gif
            $name = $path.'.gif';
            $result = imageGIF($newImg, $name);
            break;
        case 2:       //jpg
            $name = $path.'.jpg';
            $result = imageJPEG($newImg,$name);
            break;
        case 3:       //png
            $name = $path.'.png';
            $result = imagePng($newImg, $name);
            break;
        }
        imagedestroy($newImg);
        return $name;
        // return $newName;
    }
 
    /* 内部使用的私有方法，用于加水印时复制图像 */
    private function copyImage($groundImg, $waterImg, $pos, $waterInfo){
        imagecopy($groundImg, $waterImg, $pos["posX"], $pos["posY"], 0, 0, $waterInfo[0],$waterInfo[1]);
        imagedestroy($waterImg);
        return $groundImg;
    }
 
    /* 内部使用的私有方法，处理带有透明度的图片保持原样 */
    private function kidOfImage($srcImg, $size, $imgInfo){
        $newImg = imagecreatetruecolor($size["width"], $size["height"]);
        $otsc = imagecolortransparent($srcImg);
        if( $otsc >= 0 && $otsc < imagecolorstotal($srcImg)) {
            $transparentcolor = imagecolorsforindex( $srcImg, $otsc );
            $newtransparentcolor = imagecolorallocate(
                $newImg,
                $transparentcolor['red'],
                $transparentcolor['green'],
                $transparentcolor['blue']
            );
            imagefill( $newImg, 0, 0, $newtransparentcolor );
            imagecolortransparent( $newImg, $newtransparentcolor );
        }
        imagecopyresized( $newImg, $srcImg, 0, 0, 0, 0, $size["width"], $size["height"], $imgInfo[0], $imgInfo[1] );
        imagedestroy($srcImg);
        return $newImg;
    }
}